package org.javaboy.json_login01.controller;

import jakarta.servlet.http.HttpSession;
import org.javaboy.json_login01.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public String login(@RequestBody User user, HttpSession session) {
        try {
            //构造一个未经过认证的令牌
            UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(user.getUsername(),
                    user.getPassword());
            //这个就是认证方法，就是登录方法，返回值就是认证成功的对象
            Authentication auth = authenticationManager.authenticate(authRequest);
            SecurityContextHolder.getContext().setAuthentication(auth);
            //注意，这里需要手动将登录用户信息存入到 HttpSession，这样才能确保当前会话的后续请求能够在 SecurityContextHolderFilter 过滤器拿到 用户信息
            session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
            return auth.getName();
        } catch (AuthenticationException e) {
//            throw new RuntimeException(e);
            //用户名、密码错误，账户状态不对等等，都会抛出异常
            return e.getMessage();
        }
    }
}
